package com.winz.cultureapp.widge;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.winz.cultureapp.R;
import com.winz.cultureapp.utils.AppUtils;
import com.winz.cultureapp.utils.FormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间选择器
 */
public class TimerSelector {

    private Context context;
    private View mTimeView;
    private int flagTime; // 用于多少个时间选择器同时使用时
    private String timeStyle;
    private AlertDialog dialog;
    private OkClickListener listener;

    private int arrive_year;
    private int arrive_month;
    private int arrive_day;
    private int arrive_hour = -1;
    private int arrive_min = -1;
    private final Button mBtn_ok;

    private final DatePicker datePicker;
    private final TimePicker timePicker;

    public TimerSelector(Context context,String timeStyle){
        this.context = context;
        this.timeStyle = timeStyle;

        dialog = new AlertDialog.Builder(context).create();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.show();

        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (AppUtils.getScreenWidth((Activity) context)); //设置宽度
        dialog.getWindow().setAttributes(lp);
        Window window = dialog.getWindow();
        window.setContentView(R.layout.date_time_picker);

        datePicker = (DatePicker)window.findViewById(R.id.new_act_date_picker);
        timePicker = (TimePicker)window.findViewById(R.id.new_act_time_picker);
        mBtn_ok = (Button) window.findViewById(R.id.btn_ok);



        // 解析时间格式,是否需要显示timePicker
        if (isShowTime()){
            timePicker.setVisibility(View.VISIBLE);
        }else{
            timePicker.setVisibility(View.GONE);
        }

        if (isShowDate()){
            datePicker.setVisibility(View.VISIBLE);
        }else {
            datePicker.setVisibility(View.GONE);
        }


        // Change DatePicker layout
        LinearLayout dpContainer = (LinearLayout) datePicker.getChildAt(0)   ;   // LinearLayout
        LinearLayout dpSpinner = (LinearLayout)dpContainer.getChildAt(0);       // 0 : LinearLayout; 1 : CalendarView
        for(int i = 0; i < dpSpinner.getChildCount(); i ++) {
//            NumberPicker numPicker = (NumberPicker)dpSpinner.getChildAt(i);     // 0-2 : NumberPicker
            LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params1.leftMargin = 10;
            params1.rightMargin = 10;
            dpSpinner.getChildAt(i).setLayoutParams(params1);

//                  EditText cusET = (EditText)numPicker.getChildAt(0);     // CustomEditText
//                  cusET.setTextSize(14);
//                  cusET.setWidth(70);
        }

        // Change TimePicker layout
        LinearLayout tpContainer = (LinearLayout) timePicker.getChildAt(0)   ;   // LinearLayout
        LinearLayout tpSpinner = (LinearLayout)tpContainer.getChildAt(1);       // 0 : LinearLayout; 1 : LinearLayout
        for(int i = 0; i < tpSpinner.getChildCount(); i ++) {
            // child(1) is a TextView ( : )
            if (i == 1) {
                continue;
            }
//            NumberPicker numPicker = (NumberPicker)tpSpinner.getChildAt(i);     // 0 : NumberPicker; 1 : TextView; 2 : NumberPicker

            LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params3.leftMargin = 0;
            params3.rightMargin = 10;
            tpSpinner.getChildAt(i).setLayoutParams(params3);

//                  EditText cusET = (EditText)numPicker.getChildAt(0);     // CustomEditText
//                  cusET.setTextSize(14);
//                  cusET.setWidth(70);
        }


        dialog.dismiss();
    }

    private boolean isShowDate() {
        return timeStyle.contains("y");
    }

    private boolean isShowTime() {

        return timeStyle.contains("H");
    }

    public void setOkClickListener(OkClickListener listener) {
        this.listener =listener;
    }

    public interface OkClickListener{
        void okClick(View view, String date, long time, int flag);
    }

    public void show(View timeView, int flag){
        mTimeView = timeView;
        this.flagTime = flag;
        // Init DatePicker
        int year;
        int month;
        int day;
        int hour = -1;
        int minute = -1;

        String oldTime = "";
        if (mTimeView instanceof TextView){
            oldTime = ((TextView) mTimeView).getText().toString();
        }else if (mTimeView instanceof EditText){
            oldTime = ((EditText) mTimeView).getText().toString();
        }

        if (TextUtils.isEmpty(oldTime)) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            year = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH);
            day = c.get(Calendar.DAY_OF_MONTH);

            hour = c.get(Calendar.HOUR_OF_DAY);
            minute = c.get(Calendar.MINUTE);
        } else {
            /**
             * 将控件上的时间显示出来
             */
            SimpleDateFormat format = new SimpleDateFormat(timeStyle);
            Date date = null;
            try {
                date = format.parse(oldTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (date != null){
                year = Integer.parseInt(FormatUtils.millis2Str(date.getTime(),"yyyy"));
                month = Integer.parseInt(FormatUtils.millis2Str(date.getTime(),"MM")) -1;
                day = Integer.parseInt(FormatUtils.millis2Str(date.getTime(),"dd"));
                if (isShowTime()){
                    hour = Integer.parseInt(FormatUtils.millis2Str(date.getTime(),"HH"));
                    minute = Integer.parseInt(FormatUtils.millis2Str(date.getTime(),"mm"));
                }

            }else {
                year = arrive_year;
                month = arrive_month;
                day = arrive_day;
                if (isShowTime()){
                    hour = arrive_hour;
                    minute = arrive_min;
                }

            }
        }
        datePicker.init(year, month, day, null);

        if (isShowTime()){
            timePicker.setIs24HourView(true);
            timePicker.setCurrentHour(hour);
            timePicker.setCurrentMinute(minute);
        }


        mBtn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                arrive_year = datePicker.getYear();
                arrive_month = datePicker.getMonth()+1;
                arrive_day = datePicker.getDayOfMonth();
                if (isShowTime()){
                    arrive_hour = timePicker.getCurrentHour();
                    arrive_min = timePicker.getCurrentMinute();
                }
                String str = arrive_year + "-" + arrive_month + "-" + arrive_day + (arrive_hour !=-1? (" "+arrive_hour + ":" + arrive_min):"");
                SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d"+(arrive_hour !=-1? " HH:mm":""));//固定格式
                SimpleDateFormat style = new SimpleDateFormat(timeStyle);//用户传进来的格式
                try {
                    Date newDate = format.parse(str);
                    long time = newDate.getTime();
                    String data = style.format(newDate);
                    listener.okClick(v,data,time,flagTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 关闭对话框
     */
    public void dismiss() {
        dialog.dismiss();
    }
}
